package com.wp.controller;
import java.lang.RuntimeException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wp.entity.User;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller // 控制器
//@Scope("prototype") // 没必要
@RequestMapping("/user")
public class UserController{

    public UserController() {
    }

    @RequestMapping("/induction")
    public ModelAndView hello1(@RequestParam String name){
        /**
         * Model：模型 作用封装数据
         * View： 视图 作用显示数据
         */
        ModelAndView modelAndView = new ModelAndView();

        // 设置模型数据
        modelAndView.addObject("userName",name);


        // 设置视图名称
        modelAndView.setViewName("index");

        return modelAndView;
    }

//    // 捕获异常信息
//    @RequestMapping(value = "/exception")
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e,HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "view";
//    }

    @GetMapping(value = "/view")
    public String View1(Model model,@RequestParam (defaultValue = "wp",required = false)String name){
        model.addAttribute("wp",name);
        if (!name.equals("鹏程")){
            // 页面跳转
            throw new RuntimeException("用户名有误");
        }
        return "hello";
    }

    @RequestMapping(value = "/write1")
    @ResponseBody // 告知SpringMvc 我这里不进行页面跳转
    public User write(){
        User user = new User();
        user.setName("wp");
        user.setAge(20);
        return user;
    }
}
